package com.struts2.service;

import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.hibernate.HibernateUtil;
import com.struts2.model.Designer;

public class LoginService {
	
	
	public boolean verifyLogin(String username, String password) {
		
		System.out.println("verifyLogin called");
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		String hql = "SELECT d.username, d.password FROM Designer d"
				+	" where d.username = :username"
				+   " and d.password = :upw"
				+ 	" and d.approval = 1";
		
		Query query = session.createQuery(hql);
		query.setString("username", username);
		query.setString("upw", password);
		
		int count = 0;
		
		for(@SuppressWarnings("rawtypes")
		Iterator it = query.iterate(); it.hasNext();) {
			it.next();
			count++;
		}
		
		session.getTransaction().commit();
		session.close();
//		sessionFactory.close();
		
		if (count == 1) {
			return true;
		}
		return false;
	}
	
	public boolean verifyCustomerLogin(String username, String password) {
		
		System.out.println("verifyCustomerLogin called");
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		String hql = "SELECT c.name, c.phone_number FROM Customer c"
				+	" where c.name = :username"
				+   " and c.phone_number = :upw";
		
		Query query = session.createQuery(hql);
		query.setString("username", username);
		query.setString("upw", password);
		
		int count = 0;
		
		for(@SuppressWarnings("rawtypes")
		Iterator it = query.iterate(); it.hasNext();) {
			it.next();
			count++;
		}
		
		session.getTransaction().commit();
		session.close();
		//sessionFactory.close();
		if (count == 1) {
			return true;
		}
		return false;
	}
	

}
